# -*- coding: utf-8 -*-
"""
    账号管理
"""
from flask import Blueprint,request,redirect,jsonify
from common.libs.Helper import ops_render,iPagination,get_current_date
from common.models.User import User
from common.libs.UrlManager import UrlManager
from common.libs.UserService.UserService import UserService
from common.models.log.AppAccessLog import AppAccessLog
from application import app,db
from sqlalchemy import or_


route_account = Blueprint( 'account_page',__name__ )

@route_account.route( "/index" )
def index():

    resp_data = {} # 返回的内容
    req = request.values # 获取请求的参数
    query = User.query # 进行数据库查询的对象

    page = int(req['p']) if ( 'p' in req and req['p'] ) else 1 # 获取页面

    # 如果打开首页时，包含混合查询的关键字，在请求头里，则要进行查询
    if 'mix_kw' in req:
        # 定义规则，ilike可忽略大小写，规则：查询用户名中包含关键字和查询手机号里包含关键字的字段
        rule = or_( User.nickname.ilike("%{0}%".format(req['mix_kw'])), User.mobile.ilike("%{0}%".format(req['mix_kw'])) )
        query = query.filter(rule)

    # 如果打开首页时，包含状态查询的关键字，在请求头里，则要进行查询
    if 'status' in req and int(req['status']) > -1:
        query = query.filter( User.status == int(req['status']) )

    page_params = {
        'total': query.count(), # 获取一共有几条数据
        'page_size': app.config['PAGE_SIZE'], # 每页显示多少条
        'page': page, # 当前页码
        'display': app.config['PAGE_DISPLAY'], # 显示多少页
        'url': request.full_path.replace("&p={}".format(page), '')
    }

    pages = iPagination( page_params )
    offset = ( page - 1 ) * app.config['PAGE_SIZE'] # 偏移量
    limit = app.config['PAGE_SIZE'] * page

    list = query.order_by( User.uid.desc() ).all()[offset:limit] # 根据uid查询所有用户，倒序排序，加上分页

    resp_data['list'] = list
    resp_data['pages'] = pages
    resp_data['search_con'] = req
    resp_data['status_mapping'] = app.config['STATUS_MAPPING']

    return ops_render( "account/index.html", resp_data)



@route_account.route( "/info" )
def info():

    resp_data = {}

    req = request.args # 通过 args 获取GET请求的参数
    uid = int( req.get('id', 0) )

    # 如果没有取到id，则跳转回列表页面
    if uid < 1:
        return redirect(UrlManager.buildUrl('/account/index'))

    info = User.query.filter_by( uid = uid ).first()

    if not info:
        return redirect(UrlManager.buildUrl('/account/index'))

    access_log_list = AppAccessLog.query.filter_by( uid = uid ).limit(6).all()  # 查询用户操作记录

    resp_data['info'] = info
    resp_data['access_log_list'] = access_log_list

    return ops_render( "account/info.html", resp_data )



# 编辑和新建是同一个接口
@route_account.route( "/set", methods=["GET", "POST"] )
def set():

    default_pwd = '******' # 默认展示的密码

    if request.method == 'GET':
        resp_data = {}
        user_info = None

        req = request.args
        uid = int(req.get('id', 0))

        if uid:
            user_info = User.query.filter_by(uid = uid).first()

        resp_data['user_info'] = user_info

        return ops_render( "account/set.html", resp_data )

    else:
        resp = {
            'code': 200,
            'msg': '操作成功',
            'data': {}
        }

        req = request.values

        id = req['id'] if 'id' in req else 0  # 用户id
        nickname = req['nickname'] if 'nickname' in req else '' # 用户昵称
        mobile = req['mobile'] if 'mobile' in req else '' # 用户手机
        email = req['email'] if 'email' in req else '' # 用户邮箱
        login_name = req['login_name'] if 'login_name' in req else '' # 登录用户名
        login_pwd = req['login_pwd'] if 'login_pwd' in req else '' # 登录密码

        if nickname is None or len(nickname)<1:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的昵称'
            return jsonify(resp)

        if mobile is None or len(mobile)<1:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的手机号码'
            return jsonify(resp)

        if email is None or len(email)<1:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的邮箱'
            return jsonify(resp)

        if login_name is None or len(login_name)<1:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的登录用户名'
            return jsonify(resp)

        if login_pwd is None or len(login_pwd)<6:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的登录密码'
            return jsonify(resp)

        has_in = User.query.filter(User.login_name == login_name, User.uid != id).first()  # 查询登录用户名是否重复

        if has_in:
            resp['code'] = -1
            resp['msg'] = '登录用户名已存在'
            return jsonify(resp)

        user_info = User.query.filter_by(uid=id).first()

        if user_info:
            model_user = user_info
        else:
            model_user = User() # 创建一个User对象
            model_user.created_time = get_current_date()
            model_user.login_salt = UserService.geneSalt()

        model_user.nickname = nickname
        model_user.mobile = mobile
        model_user.email = email
        model_user.login_name = login_name

        if login_pwd != default_pwd:
            model_user.login_pwd = UserService.genePwd(login_pwd, model_user.login_salt)

        model_user.updated_time = get_current_date()

        db.session.add(model_user)
        db.session.commit()

        return jsonify(resp)



# 删除/恢复用户
@route_account.route("/ops", methods=["POST"])
def ops():
    # 统一返回内容
    resp = {'code': 200, 'msg': '操作成功', 'data': {} }

    req = request.values

    id = req['id'] if 'id' in req else 0 # 用户id
    act = req['act'] if 'act' in req else '' # 操作行为

    if not id:
        resp['code'] = -1
        resp['msg'] = '请选择要操作的账号'
        return jsonify(resp)

    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = '操作有误请重试'
        return jsonify(resp)

    user_info = User.query.filter_by(uid=id).first() # 根据id查询

    # 如果用户不存在
    if not user_info:
        resp['code'] = -1
        resp['msg'] = '指定账号不存在'
        return jsonify(resp)

    # 如果是删除
    if act == 'remove':
        user_info.status = 0 # 把用户状态码改为0
    # 如果是恢复
    elif act == 'recover':
        user_info.status = 1  # 把用户状态码改为1

    user_info.update_time = get_current_date() # 更新 更新时间

    db.session.add(user_info)
    db.session.commit()

    return jsonify(resp)
